package org.example.slave.util;

import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import org.example.slave.channel.MyChannel;
import org.example.slave.packet.HeaderPacket;

import java.io.ByteArrayOutputStream;

/**
 * @author dingrui
 * @since 2022/2/16
 * @description 自定义channel的收发操作
 * @see org.example.slave.channel.MyChannel
 */
@UtilityClass
public class MyChannelUtil {

    @SneakyThrows
    public void write(MyChannel ch, byte[] data) {
        ch.write(data);
    }

    @SneakyThrows
    public void write(MyChannel ch, byte[]... data) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        for (byte[] bytes : data) out.write(bytes);
        ch.write(out.toByteArray());
    }

    @SneakyThrows
    public void write(MyChannel ch, byte[] data, int seqNo) {
        // 构建header
        HeaderPacket h = new HeaderPacket();
        h.setPacketBodyLength(data.length);
        h.setPacketSequenceNumber(((byte) (seqNo)));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // head
        out.write(h.toBytes());
        // body
        out.write(data);
        ch.write(out.toByteArray());
    }

    public byte[] readBytes(MyChannel ch, int len) {
        return ch.read(len);
    }
}
